<?php


namespace app\services;


use app\model\CommodityLotteryLog;
use app\model\MoneyLog;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;

class Lottery
{


    /**
     * Lottery constructor.
     * @param CommodityLotteryLog $commodityLotteryLog
     */
    public function __construct(CommodityLotteryLog $commodityLotteryLog)
    {
        $this->model = $commodityLotteryLog;
    }


    /**
     * 幸运豪礼
     * 一.幸运豪礼(该奖池奖品全为汽车)：所有用户第一次免费抽奖，后续抽奖消耗5积分/次，可一直抽奖，每日无上限。大奖中奖为名额制，即用户消耗的积分总和达到该奖池最贵商品的积分数额后，即产生一个中奖名额。后续用户继续抽奖，中奖几率为1‰(后台可设置)。每日用户在该奖池消耗的积分的10%(后台可设置)作为第二天抽奖的积分奖励拨出。拨出的积分奖励与名额产出积分累计无关。用户抽奖结果总共有三类：未中奖，大奖，积分奖励。未中奖概率为90%，积分奖励概率为10%，大奖概率为1‰(当有名额时，后台可设置)。抽中积分奖励50-100积分(随机)观看一次广告后可获得，用户累计抽中积分奖励≥今日拨出总积分时，后续用户今日不可再抽中积分奖励。
     * 例：幸运豪礼奖池中有N个奖品，最贵的商品为一辆价值20W的汽车，对应的价值是2000W积分。则需要用户抽奖消耗的积分≥2000W时，则产生一个中奖名额，后续所有用户中奖率为1‰。在昨日抽奖活动中，所有用户消耗了10W积分来抽奖，则今天拨出1W积分给予用户的抽奖奖励。
     * 场景：今日用户已抽取了9995积分奖励，当下一位用户再抽中积分奖励时，仍奖励50-100积分。当用户抽取的积分奖励总和≥今日拨付的1W积分时，今日后续用户不可再抽中积分奖励，只能抽中未中奖或极低概率中大奖(当有名额时)。
     * @param $res
     * @return array
     */
    public function luckyGift($res)
    {
        try {
            //查看数据库对应最大的商品的积分是多少
            $list = Db::name('commodity_lottery')
                ->alias('a')
                ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
                ->where('b.lottery_stock', '>', 0)
                ->field('a.*,b.lottery_stock,b.price,b.name as goods_name,b.image')
                ->limit(1)
                ->order('b.price desc')
                ->find();
            //查找目前消耗的积分是多少
            $log = $this->model->where(['type' => 1, 'is_lottery' => 1])->find();
            $where[] = ['type', '=', 8];
            if ($log) {
                $where[] = ['created_time', 'between', [$log->created_time, date('Y-m-d H:i:s', time())]];
            }
            //查看上次中奖商品到现在用户抽奖消耗的积分
            $integral = Db::name('money_log')->where($where)->sum('money');


            //如果消耗积分有达到商品最大积分目标
            $rand_integral = rand(50, 100);
            if ($integral >= $list['price']) {
                //查看昨日消耗积分
                $yes_integral = Db::name('money_log')->where(['type' => 8])->whereTime('created_time', 'between', [DateTime()['y_s'], DateTime()['y_e']])->sum('money');
                //查看今天发放积分
                $today_intergral = Db::name('money_log')->where(['type' => 9])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->sum('money');
                //昨日消耗积分大于0并且今天发放积分小于昨日消耗积分
                if ($yes_integral > 0 && $today_intergral < ($yes_integral * 0.1)) {
                    $arrs = array(
                        ['id' => 1, 'name' => '谢谢参与！', 'rate' => 70 - $list['rate'], 'goods_id' => '', 'is_lottery' => 0, 'image' => ''],
                        ['id' => 2, 'name' => $rand_integral . '积分奖励！', 'rate' => 30, 'goods_id' => '', 'is_lottery' => 2, 'image' => ''],
                        ['id' => 3, 'name' => $list['goods_name'], 'rate' => $list['rate'], 'goods_id' => $list['goods_id'], 'is_lottery' => 1, 'image' => $list['image']],
                    );
                    foreach ($arrs as $key => $val) {
                        $arr[$val['id']] = $val['rate'];
                    }
                    $rid = $this->getRand($arr);
                    $res = $arrs[$rid - 1]; //中奖项
                    unset($res['rate']);
                }
            }
            $res['lottery_id'] = $list['id'];
            $res['rand_integral'] = $rand_integral;
            return $res;
        } catch (\Exception $exception) {
            throw new HttpException(500, '抽奖信息错误' . $exception->getMessage());
        }
    }


    /**
     * 其他专区
     * 200积分区：抽奖固定消耗200积分/次，6次必中，每天只能中奖一次。第5次有1%概率中奖，每有100个抽奖第五次的用户没中奖则产生一个中奖名额，名额可累加。1-4次不能中奖，每天次数清零。
     * 场景1：用户抽奖未满6次，未中奖，次日次数清零。
     * 场景2：用户抽奖第五次中奖，显示用户已中奖，今日不能再抽，次日从0开始。
     * 场景3：用户抽满6次中奖，显示用户已中奖，今日不能再抽，次日从0开始。
     * @param int $user_id
     * @param array $res
     * @param int $type
     * @return array
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function other(int $user_id, array $res, int $type)
    {

        $goods_lottery = Db::name('commodity_lottery')
            ->alias('a')
            ->field('a.id as lottery_id,a.goods_id,b.name,b.image')
            ->leftJoin('commodity_goods b', 'a.goods_id = b.id')
            ->where(['a.type' => $type])
            ->select()
            ->toArray();
        if (!empty($goods_lottery)) {
            //查看今天是否中奖
            $lottery_log = $this->model->where(['user_id' => $user_id, 'type' => $type])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->column('is_lottery');
            if (in_array(1, $lottery_log)) {
                throw new HttpException(500, '今天已经中奖了，请明日再来哦~');
            }
            //查看今天抽奖次数
            $lottery_count = count($lottery_log) + 1;

            switch ($lottery_count) {
                case 5:
                    //查看所有用户达到五次并未中奖的次数
                    $five_not_lottery = Db::name('commodity_lottery_log')->field('count(id) as nums')->where(['is_lottery' => 0, 'type' => $type])->having('nums >= 5')->find();
                    $five_not_lottery = floor(floor($five_not_lottery['nums'] / 5) / 100);
                    //查看所有用户第五次中奖的次数
                    $five_yes_lottery = Db::name('commodity_lottery_log')->where(['is_lottery' => 1, 'is_five_lottery' => 1, 'type' => $type])->count();
                    if ($five_not_lottery > $five_yes_lottery) {
                        //派发第五次中奖
                        //查看奖池商品
                        if (!empty($goods_lottery)) {
                            //积分百分比
                            $no_rate = Db::name('system_config')->where(['id' => 88])->value('value');
                            //中奖百分比
                            $yes_rate = Db::name('system_config')->where(['id' => 91])->value('value');
                            if ($no_rate + $yes_rate != 100) {
                                throw new HttpException(500, '抽奖设置错误');
                            }
                            $arrs = array(
                                ['id' => 1, 'name' => '谢谢参与！', 'rate' => $no_rate],
                                ['id' => 2, 'name' => '中奖', 'rate' => $yes_rate],
                            );
                            foreach ($arrs as $key => $val) {
                                $arr[$val['id']] = $val['rate'];
                            }
                            $rid = $this->getRand($arr);
                            $res = $arrs[$rid - 1];
                            //已中奖随机一个商品
                            if ($res['id'] == 2) {
                                //派发商品
                                $array_key = array_rand($goods_lottery, 1);
                                $res = $goods_lottery [$array_key];
                                $res['num'] = 6 - $lottery_count;
                                $res['is_lottery'] = 1;
                                $res['is_five_lottery'] = 1;
                            }
                        }
                    }
                    break;
                case 6://中奖
                    $array_key = array_rand($goods_lottery, 1);
                    $res = $goods_lottery [$array_key];
                    $res['num'] = 6 - $lottery_count;
                    $res['is_lottery'] = 1;
                    $res['is_five_lottery'] = 0;
                    break;
            }
        }

        return $res;

    }


    /**
     * 计算中奖概率
     * @param $proArr
     * @return int|string
     */
    public function getRand($proArr)
    {
        $rs = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $rs = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset($proArr);
        return $rs;
    }

}